<?php
require_once('configuration.php');

foreach ( $NODE_NAMES as $key => $value) {
  $state = get_sensor_state($key);
  echo "$value:$state<br/>"; 
} 

//----------------------------------
// FUNCTIONS
//----------------------------------
function get_sensor_state($id){
// Returns the state of the sensor OK|ERROR:Last measurement
  global $UPLOAD_INTERVAL;
  $latest = get_last_sensor_file_timestamp($id);
  $now = time();
  $state = "ERROR";
  if (($now-$latest) < $UPLOAD_INTERVAL )
    $state = "OK";
  return $state . ":" . date(DATE_RFC822, $latest);
  //return $state . ":" . $latest;
}
function get_last_sensor_file_timestamp($id){
  // Returns the unix timestamp of the last sensor file
  // OR -1 if there is an error
  global $UPLOAD_FOLDER;
  $directory = $UPLOAD_FOLDER;
  $files = scandir($directory, 1); //sort alphabetical in descending order.
  $filename = ""; 
  foreach ( $files as $file) {
    $length = strlen($id);
    if ( strncasecmp($file,$id,$length) == 0 ) {
      $filename = $file;
      break;
    }
  }
  if (strlen($filename) < 1 )return -1;
  $date = _getFilenameDate($filename);
  return $date;
}

function _getFilenameDate($filename){
  //Returns the unix timestamp from filename
  
  // <SENSOR_ID>_<JAVA_TS>.amr
  //JAVA TS java millis: number of milliseconds since January 1, 1970, 00:00:00 GMT
  //Unix timestamp is a long integer containing the number of seconds from the Unix Epoch (January 1 1970 00:00:00 GMT)
  $index_1 = strpos($filename,"_",0);
  $index_2 = strpos($filename,".",0);
  //$millis = $filename . "=>" . substr($filename, $index_1+1,$index_2-$index_1-1);
  //$millis = $millis . "=>" . floatval  ( substr($filename, $index_1+1,$index_2-$index_1-1) )/1000;
  $ts = floatval  ( substr($filename, $index_1+1,$index_2-$index_1-1) )/1000;
  return $ts;
}




?>